package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.domain.Goods;
import com.qf.domain.User;
import com.qf.utils.DateSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;


public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner = new QueryRunner(DateSourceUtil.getDataSource());

    @Override
    public User selectByUserName(String username) {
        String sql = "select * from tb_user where username=?";
        try {
            return queryRunner.query(sql, new BeanHandler<>(User.class), username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(User user) {

        String sql = " insert into tb_user values(null,?,?,?,?,?,?,?) ";
        Object[] params = {user.getUsername(), user.getPassword(), user.getEmail(), user.getGender(), user.getFlag(), user.getRole(), user.getCode()};
        try {
            queryRunner.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<User> selectAll(String toString, List<Object> params, boolean flag) {
        String sql = "";
        if (!flag) {
            sql = " SELECT * FROM tb_user " + toString + " AND flag=1  ";
        }
        try {
            return queryRunner.query(sql, new BeanListHandler<>(User.class), params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int did) {
        String sql=" DELETE FROM `tb_user` WHERE `id`=? ";
        try {
            queryRunner.update(sql,did);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User selectById(Integer uid) {
        String sql = " SELECT * FROM tb_user WHERE id=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(User.class),uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
